<template>
  <div class="outer" id="screenContent"
    :class="[isTemplate && 'template-view-box', readonly && 'view-file-mindElixir']">
    <div id="map"></div>
  </div>
</template>

<script setup lang="ts">
import {
  ref, watch, onMounted, getCurrentInstance
} from 'vue'
import { preview, getShareInfo, saveContent, uploadTemplateCover } from "@/api/common";
import { getTemplateInfo, saveTemplateContent, saveTemplate } from '@/api/template'
import { saveVersion } from '@/api/version'
// import MindElixir from "mind-elixir";
import MindElixir from './MindElixir'
import nodeMenu from '@mind-elixir/node-menu'
import '@mind-elixir/node-menu/dist/style.css'
import { useRoute } from "vue-router"
import useCommonStore from '@/store/common'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const commonStore = useCommonStore()

const route = useRoute()
const emit = defineEmits(["editorLoadingChange", 'renderFinish', 'changeLatelySave'])
const { proxy } = getCurrentInstance()
const props = defineProps({
  id: {
    type: String
  },
  readonly: {
    type: Boolean
  },
  isPrivew: {
    type: Boolean,
    default: false
  },
  formShare: {
    type: Boolean
  },
  infoLists: {
    type: Object,
    default: () => {
      return {};
    }
  },
  isTemplate: {
    type: Boolean,
    default: false
  },
  docInfo: {
    type: Object,
    default: () => {
      return {};
    }
  }
})
const me = ref()
const content = ref({})
const nodeId = ref()
const MindElixirList = [0, 1, 2]
const type = ref(2)

watch(() => props.isPrivew, (newVal, oldVal) => {
  if (newVal != oldVal) {
    if (newVal == true) {
      // this.$refs.version.getVersionAll()
    }
  }
})
onMounted(() => {
  getData()
})
watch(() => props.id, (newV) => {
  getData()
})
async function downFile(item: any) {
  let storeDownItem = {
    id: item.id,
    name: item.name,
    isFinish: false,
    downTime: new Date().getTime()
  }
  let soteDownList = commonStore.downFileList
  soteDownList.push(storeDownItem)
  commonStore.setDownLoadFileList(soteDownList)
  const blob = await me.value.exportPng() // Get a Blob!
  if (!blob) return
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${item.name}.png`
  a.click()
  URL.revokeObjectURL(url)
  soteDownList.forEach((item) => {
    if (item.downTime == storeDownItem.downTime) {
      item.isFinish = true
    }
  })
  commonStore.setDownLoadFileList(soteDownList)
  proxy.$notify({
    title: $t('message.buttons.download'),
    messag: $t('message.message.downloadSuccess'),
    type: 'success',
    positon: 'bottom-right'
  })
}
function getData() {
  content.value = {}
  if (props.id) {
    nodeId.value = props.id
  }
  if (nodeId.value) {
    let fun = preview
    if (props.formShare) {
      fun = getShareInfo
    }
    if (route.query.type == 'template' || props.isTemplate) {
      fun = getTemplateInfo
    }
    fun(nodeId.value).then((res) => {
      if (res.data.code == 0 && res.data.data) {
        if (res.data.data.content && res.data.data.content.startsWith("{")) {
          let resData = JSON.parse(res.data.data.content).content;
          content.value = JSON.parse(resData);
        }
        if (res.data.data.otherJson) {
          type.value = JSON.parse(res.data.data.otherJson).type
        }
        mindInit()
      }
    }).catch(() => {})
  }
}
function mindInit() {
  me.value = new MindElixir({
    locale: locale.value == 'zh-CN' ? 'zh_CN' : locale.value,
    el: "#map",
    direction: MindElixirList[type.value],
    draggable: props.readonly ? false : true, // 启用拖动
    contextMenu: props.readonly ? false : true, // 启用右键菜单
    toolBar: true, // 启用工具栏
    nodeMenu: props.readonly ? false : true, // 启用节点菜单
    keypress: props.readonly ? false : true, // 启用快捷键
    editable: props.readonly ? false : true, // 可否编辑
    allowUndo: props.readonly ? false : true,
    mouseSelectionButton: 2,
  });
  me.value.install(nodeMenu)
  emit('renderFinish')
  me.value.bus.addListener('operation', (operation: any) => {
    if (me.value.inputDiv) {
      if (operation.obj.root) {
        me.value.inputDiv.style.margin = 0
        me.value.inputDiv.style.outline = "2px solid #000"
        me.value.inputDiv.style.width = "100%"
        me.value.inputDiv.style.height = "100%"
        // me.value.inputDiv.style.lineHeight = "57px"
        me.value.inputDiv.style.color = "black"
      } else {
        me.value.inputDiv.style.margin = 0
        me.value.inputDiv.style.outline = "3px solid #000"
      }
    }
    if (operation.name !== 'beginEdit') {

    }
  })
  if (!content.value || JSON.stringify(content.value) == '{}') {
    me.value.init(MindElixir.new($t('message.text.pleaseEnterText')))
    MindElixir.E("node-id");
  } else {
    me.value.init(content.value)
    MindElixir.E("node-id");
  }

}
function createImg(item) {
  proxy.$eventBus.$emit('changeSaveLoading', true)
  html2canvas(document.getElementById('screenContent'), {
    useCORS: true,
    backgroundColor: null
  }
  ).then((canvas) => {
    const dataUrl = canvas.toDataURL('images/jpg')
    let formData = new FormData();
    formData.append('file', dataURLtoFile(dataUrl, item.name))
    formData.append('module', `/jvs-knowledge-ui/${props.docInfo.id}/fileCover`)
    uploadTemplateCover(formData).then(res => {
      saveTemp({
        ...props.docInfo,
        coverUrl: res.data.data.fileLink,
        coverFilePath: res.data.data.fileName,
        coverBucketName: res.data.data.bucketName,
      })
    }).catch(err => {
      proxy.$eventBus.$emit('changeSaveLoading', false)
    })
  })
}
//修改模板的封面
function saveTemp(item) {
  saveTemplate(Object.assign({}, item, {
    typeId: item.typeId,
    templateType: 'edit',
    ...item
  })).then(res => {
    if (res.data.code == 0) {
      proxy.$notify({
        title: $t('message.message.saveTemplateSuccess'),
        type: "success",
        position: "bottom-right",
      });
    }
  }).finally(f => {
    proxy.$eventBus.$emit('changeSaveLoading', false)
  })
}
function dataURLtoFile(dataurl, filename) {
  // 获取到base64编码
  const arr = dataurl.split(',')
  // 将base64编码转为字符串
  const bstr = window.atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n) // 创建初始化为0的，包含length个元素的无符号整型数组
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {
    type: 'image/png'
  })
}
function handleSave() {
  let fun = saveContent
  if (route.query.type == 'template') {
    createImg(props.docInfo)
    fun = saveTemplateContent
  }
  let viewString = me.value.getDataString();
  fun(nodeId.value, { content: viewString, otherJson: JSON.stringify({ type: me.value.direction }) }).then(res => {
    if (res.data.code == 0) {
      proxy.$notify({
        title: $t('message.message.saveSuccess'),
        type: "success",
        position: "bottom-right",
      });
      emit("changeLatelySave", new Date())
    }
  });

}
function saveVersionFun(type) {
  let viewString = me.value.getDataString();
  saveVersion({
    dcId: props.id,
    content: JSON.stringify(
      { content: viewString, otherJson: JSON.stringify({ type: me.value.direction }) }
    )
  }).then(res => {
    if (res.data.code == 0) {
      if (type) {
        proxy.$notify({
          title: $t('message.message.generatedVersionSuccess'),
          type: "success",
          position: "bottom-right",
        });
      }
    }
  })
}
function endSwitchVersion(content, type) {
  // this.$refs.version.handleClose()
  if (type == 'handleVersion') {
    let oldCont = JSON.parse(content)
    content.value = JSON.parse(oldCont.content)
    type.value = JSON.parse(oldCont.otherJson).type
    mindInit()
  } else {
    // this.$refs.aomaoContinar.verSionChangeHtml(content)
  }
}
function changeEditStatus(val) {
  if (document.getElementsByClassName("node-menu")[0]) {
    document.getElementsByClassName("node-menu")[0].setAttribute("hidden", "hidden");
  }
  if (val) {
    me.value.disableEdit()
  } else {
    me.value.enableEdit()
  }
}
function changeVersionContent(content, type) {
  if (type == 'handleVersion') {
    let oldCont = JSON.parse(content)
    content.value = JSON.parse(oldCont.content)
    type.value = JSON.parse(oldCont.otherJson).type
    mindInit()
  }
}

function closeShortKey() { }

defineExpose({
  handleSave,
  closeShortKey,
  changeEditStatus,
  saveVersionFun,
  downFile,
  changeVersionContent
})
</script>
<style lang="scss" scoped>
.outer {
  position: relative;
  width: 100%;
  height: 100%;
}

.view-file-mindElixir {
  height: calc(100vh - 200px);
}

#map {
  // height: 500px;
  width: 100%;
  height: 100%;

  .mind-elixir-toolbar {
    box-sizing: border-box;
  }
}

.outer #map .lt {
  width: 40px;
}
</style>
<style lang="scss">
.template-view-box {
  height: calc(100vh - 252px) !important;

  .map-canvas,
  .map-container {
    background-color: #eeeff0 !important;
  }
}
</style>